import {
  deviceConfig,
  getMediaById,
  mediaDeviceList,
  type Media,
} from '@/api/modules/lcd/lcd-device';
import { allowEditMenu, query, table } from '../data/data';
import { form, resetForm } from './form';
import { notify } from '@/utils/common/common';

export const create = () => {
  allowEditMenu.value = true;
  resetForm();
};
export const list = async () => {
  table.value.loading = true;
  const { data } = await mediaDeviceList(query.value);

  table.value.data = data.rows.map((e: Media) => {
    if (e.label && typeof e.label === 'string') {
      e.label = e.label.split(',').filter(e => !!e);
    } else {
      e.label = [];
    }
    return e;
  });
  table.value.loading = false;
  query.value.total = data.total;
};

export const edit = async (id?: string) => {
  const targetId = id ? id : table.value.keys[0];
  const { data } = await getMediaById(targetId);
  form.value = data.data;

  allowEditMenu.value = true;
  table.value.loading = false;
};

export const remove = async (id?: string) => {
  const ids = id ? [id] : table.value.keys;
  await list();
};

export const detail = () => {
  allowEditMenu.value = true;
  table.value.loading = false;
};
export const search = () => {
  query.value.pageNum = 1;
  list();
};
export const changeDisplay = async (record: Media) => {
  const { data } = await deviceConfig({
    display: record.display,
    mediaIds: [record.mediaId],
  });
  notify(data);
  list();
};

export const changeConnect = async (record: Media) => {
  const { data } = await deviceConfig({
    display: record.display,
    conn: record.conn,
    mediaIds: [record.mediaId],
  });
  notify(data);
  list();
};
